<?php

namespace addons\qingdong\model;

use think\Model;
use traits\model\SoftDelete;

/**
 *员工部门表
 */
class StaffDepartment Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdong_staff_department';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';


	//员工业绩
	public function achievement() {
		return $this->belongsTo(Achievement::class, 'id', 'obj_id')->where(['type' => 2]);
	}


	//获取部门列表
	public static function getDepartmentList() {
		$department = self::where([])->field('id,name,pid')->select();

		$data = [];
		foreach ($department as $v) {
			$data[$v['pid']][] = $v;
		}

		return self::getChilds($data, 0);
	}

	//获取部门及所有下级部门
	public static function getDepartmentLowerId($l_ids,$top=true){
		$ids=self::where(['pid' =>['in',$l_ids]])->column('id');
		if ($ids) {
			$w_ids = self::getDepartmentLowerId($ids,false);
			$ids   = array_merge($ids, $w_ids);
		}else{
			$ids=[];
		}
		if($top){
			$ids=array_merge($ids,$l_ids);
		}
		return $ids;
	}


	//生成树状结构
	private static function getChilds($data, $pid) {
		$list = [];
		if (isset($data[$pid])) {
			$list = $data[$pid];
			foreach ($list as $k => $v) {
				$v['children'] = self::getChilds($data, $v['id']);
				$list[$k]    = $v;
			}
		}

		return $list;
	}
    //获取部门列表
    public static function getList()
    {
        return self::where([])->field('id,name')->select();
    }
}
